import {
  request
} from '../../request/index'
import regeneratorRuntime from '../../lib/runtime/runtime'
import PubSub from 'pubsub-js'


// pages/recommendSong/index.js
Page({

  data: {
    day:"",
    month:"",
    recommendList:[],
    index:0
  },

  onLoad: function (options) {

    //判断用户是否登录
    let userinfo = wx.getStorageSync('userinfo');
    if(!userinfo){
      wx.showToast({
        title: '请先登录哦！',
        icon: 'none',
        success:()=>{
          wx.reLaunch({
            url: '/pages/login/index',
          });
        }
      });
    }


    this.setData({
      day:new Date().getDate(),
      month:new Date().getMonth()+1
    })

    this.getRecommendList()


    //订阅来自详情页的发布消息
    PubSub.subscribe('switchType',(msg,type)=>{
      let {recommendList , index} = this.data
      if(type === 'pre'){ //上一首
        (index === 0) && (index = recommendList.length)
        index -= 1
      }
      else if(type === 'loop'){ // 循环播放
        index = index
      }
      
      else{ //  下一首
        (index === recommendList.length-1) && (index = -1)
        index += 1
      }

      this.setData({
        index
      })
      let musicId = recommendList[index].id

      //发布消息
      PubSub.publish("musicId",musicId)

    })
  },

  //获取每日推荐数据
  async getRecommendList(){
    let {data:{data:{dailySongs}}} = await request({url:"/recommend/songs"})
    this.setData({
      recommendList:dailySongs
    })
  },
  toDetail(e){
    let id = e.currentTarget.dataset.id
    let index = e.currentTarget.dataset.index

    this.setData({
      index
    })
    wx.navigateTo({
      url: '/pages/songDetail/index?id=' + id
    });
  },

})